Python Matplotlib

Prepared By

Jayoda Kulatunga

Undergraduate Student

Pearson HND in Computing - Software Engineering

ESOFT Metro Campus

Table of Contents

Python Matplotlib

Table of Contents

Matplotlib Intro

What is Matplotlib?

Where is the Matplotlib Codebase?

Matplotlib Get Started

Installation of Matplotlib

Import Matplotlib

Checking Matplotlib Version

Matplotlib Pyplot

Pyplot

Matplotlib Plotting

Plotting x and y points

Plotting Without Line

Multiple Points

Default X-Points

Matplotlib Markers

Markers

Marker Reference

Format Strings fmt

Line Reference

Color Reference

Marker Size

Marker Color

Matplotlib Line

Linestyle

Shorter Syntax

Line Styles

Line Color

Line Width

Multiple Lines

Matplotlib Labels

Create Labels for a Plot

Create a Title for a Plot

Set Font Properties for Title and Labels

Position the Title

Matplotlib Grid

Add Grid Lines to a Plot

Specify Which Grid Lines to Display

Set Line Properties for the Grid

Matplotlib Subplot

Display Multiple Plots

The subplot() Function

Example

Title

Example

Super Title

Example

Matplotlib Scatter

Creating Scatter Plots

Compare Plots

Colors

Color Each Dot

ColorMap

How to Use the ColorMap

Size

Alpha

Combine Color Size and Alpha

Matplotlib Bars

Creating Bars

Horizontal Bars

Bar Color

Color Names

Color Hex

Bar Width

Bar Height

Matplotlib Histograms

Histogram

Create Histogram

Result:

Matplotlib Pie Charts

Creating Pie Charts

Labels

Start Angle

Explode

Shadow

Colors

Legend

Legend With Header

Matplotlib Intro 

(Click here to go back to the menu)

What is Matplotlib?

Matplotlib is a low level graph plotting library in python that serves as a visualization utility.

Matplotlib was created by John D. Hunter.

Matplotlib is open source and we can use it freely.

Matplotlib is mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform compatibility.


Where is the Matplotlib Codebase?

The source code for Matplotlib is located at this github repository https://github.com/matplotlib/matplotlib

Matplotlib Get Started

(Click here to go back to the menu)

Installation of Matplotlib

If you have Python and PIP already installed on a system, then installation of Matplotlib is very easy.

Install it using this command:

C:\Users\Your Name>pip install matplotlib

If this command fails, then use a python distribution that already has Matplotlib installed,  like Anaconda, Spyder etc.


Import Matplotlib

Once Matplotlib is installed, import it in your applications by adding the import module statement:

import matplotlib

Now Matplotlib is imported and ready to use:


Checking Matplotlib Version

The version string is stored under __version__ attribute.

Matplotlib Pyplot

(Click here to go back to the menu)

Pyplot

Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias:

import matplotlib.pyplot as plt

Now the Pyplot package can be referred to as plt.

Matplotlib Plotting

(Click here to go back to the menu)

Plotting x and y points

The plot() function is used to draw points (markers) in a diagram.

By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

Parameter 1 is an array containing the points on the x-axis.

Parameter 2 is an array containing the points on the y-axis.

If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to the plot function.

The x-axis is the horizontal axis.

The y-axis is the vertical axis.

Plotting Without Line

To plot only the markers, you can use shortcut string notation parameter 'o', which means 'rings'.

Multiple Points

You can plot as many points as you like, just make sure you have the same number of points in both axis.

Default X-Points

If we do not specify the points on the x-axis, they will get the default values 0, 1, 2, 3 etc., depending on the length of the y-points.

So, if we take the same example as above, and leave out the x-points, the diagram will look like this:

The x-points in the example above are [0, 1, 2, 3, 4, 5].

Matplotlib Markers

(Click here to go back to the menu)

Markers

You can use the keyword argument marker to emphasize each point with a specified marker:

Marker Reference

You can choose any of these markers:

Marker

Description

'o'

Circle

Try it »

'*'

Star

Try it »

'.'

Point

Try it »

','

Pixel

Try it »

'x'

X

Try it »

'X'

X (filled)

Try it »

'+'

Plus

Try it »

'P'

Plus (filled)

Try it »

's'

Square

Try it »

'D'

Diamond

Try it »

'd'

Diamond (thin)

Try it »

'p'

Pentagon

Try it »

'H'

Hexagon

Try it »

'h'

Hexagon

Try it »

'v'

Triangle Down

Try it »

'^'

Triangle Up

Try it »

'<'

Triangle Left

Try it »

'>'

Triangle Right

Try it »

'1'

Tri Down

Try it »

'2'

Tri Up

Try it »

'3'

Tri Left

Try it »

'4'

Tri Right

Try it »

'|'

Vline

Try it »

'_'

Hline

Format Strings fmt

You can also use the shortcut string notation parameter to specify the marker.

This parameter is also called fmt, and is written with this syntax:

Marker|line|color

The marker value can be anything from the Marker Reference above.

The line value can be one of the following:

Line Reference

Line Syntax

Description

'-'

Solid line

Try it »

':'

Dotted line

Try it »

'--'

Dashed line

Try it »

'-.'

Dashed/dotted line

Note: If you leave out the line value in the fmt parameter, no line will be plotted.

The short color value can be one of the following:

Color Reference

Color Syntax

Description

'r'

Red

Try it »

'g'

Green

Try it »

'b'

Blue

Try it »

'c'

Cyan

Try it »

'm'

Magenta

Try it »

'y'

Yellow

Try it »

'k'

Black

Try it »

'w'

White

Marker Size

You can use the keyword argument markersize or the shorter version, ms to set the size of the markers:

Marker Color

You can use the keyword argument markeredgecolor or the shorter mec to set the color of the edge of the markers:

You can use the keyword argument markerfacecolor or the shorter mfc to set the color inside the edge of the markers:

Use both the mec and mfc arguments to color the entire marker:

You can also use Hexadecimal color values:

Or any of the 140 supported color names.

Matplotlib Line

(Click here to go back to the menu)

Linestyle

You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line:

Shorter Syntax

The line style can be written in a shorter syntax:

linestyle can be written as ls.

dotted can be written as :.

dashed can be written as --.

Line Styles

You can choose any of these styles:

Style

Or

'solid' (default)

'-'

Try it »

'dotted'

':'

Try it »

'dashed'

'--'

Try it »

'dashdot'

'-.'

Try it »

'None'

'' or ' '

Line Color

You can use the keyword argument color or the shorter c to set the color of the line:

You can also use Hexadecimal color values:

Or any of the 140 supported color names.

Line Width

You can use the keyword argument linewidth or the shorter lw to change the width of the line.

The value is a floating number, in points:

Multiple Lines

You can plot as many lines as you like by simply adding more plt.plot() functions:

You can also plot many lines by adding the points for the x- and y-axis for each line in the same plt.plot() function.

(In the examples above we only specified the points on the y-axis, meaning that the points on the x-axis got the the default values (0, 1, 2, 3).)

The x- and y- values come in pairs:

Matplotlib Labels

(Click here to go back to the menu)

Create Labels for a Plot

With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x- and y-axis.

Create a Title for a Plot

With Pyplot, you can use the title() function to set a title for the plot.

Set Font Properties for Title and Labels

You can use the fontdict parameter in xlabel(), ylabel(), and title() to set font properties for the title and labels.

Position the Title

You can use the loc parameter in title() to position the title.

Legal values are: 'left', 'right', and 'center'. Default value is 'center'.

Matplotlib Grid

(Click here to go back to the menu)

Add Grid Lines to a Plot

With Pyplot, you can use the grid() function to add grid lines to the plot.

Specify Which Grid Lines to Display

You can use the axis parameter in the grid() function to specify which grid lines to display.

Legal values are: 'x', 'y', and 'both'. Default value is 'both'.

Set Line Properties for the Grid

You can also set the line properties of the grid, like this: grid(color = 'color', linestyle = 'linestyle', linewidth = number).

Matplotlib Subplot

(Click here to go back to the menu)

Display Multiple Plots

With the subplot() function you can draw multiple plots in one figure:

Example

Draw 2 plots:

The subplot() Function

The subplot() function takes three arguments that describes the layout of the figure.

The layout is organized in rows and columns, which are represented by the first and second argument.

The third argument represents the index of the current plot.

So, if we want a figure with 2 rows an 1 column (meaning that the two plots will be displayed on top of each other instead of side-by-side), we can write the syntax like this:

You can draw as many plots you like on one figure, just descibe the number of rows, columns, and the index of the plot.

Example

Draw 6 plots:

Title

You can add a title to each plot with the title() function:

Example

2 plots, with titles:

Super Title

You can add a title to the entire figure with the suptitle() function:

Example

Add a title for the entire figure:

Matplotlib Scatter

(Click here to go back to the menu)

Creating Scatter Plots

With Pyplot, you can use the scatter() function to draw a scatter plot.

The scatter() function plots one dot for each observation. It needs two arrays of the same length, one for the values of the x-axis, and one for values on the y-axis:

The observation in the example above is the result of 13 cars passing by.

The X-axis shows how old the car is.

The Y-axis shows the speed of the car when it passes.

Are there any relationships between the observations?

It seems that the newer the car, the faster it drives, but that could be a coincidence, after all we only registered 13 cars.

Compare Plots

In the example above, there seems to be a relationship between speed and age, but what if we plot the observations from another day as well? Will the scatter plot tell us something else?

Note: The two plots are plotted with two different colors, by default blue and orange, you will learn how to change colors later in this chapter.

By comparing the two plots, I think it is safe to say that they both gives us the same conclusion: the newer the car, the faster it drives.

Colors

You can set your own color for each scatter plot with the color or the c argument:

Color Each Dot

You can even set a specific color for each dot by using an array of colors as value for the c argument:

Note: You cannot use the color argument for this, only the c argument.

Example

Set your own color of the markers:

ColorMap

The Matplotlib module has a number of available colormaps.

A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.

Here is an example of a colormap:

This colormap is called 'viridis' and as you can see it ranges from 0, which is a purple color, up to 100, which is a yellow color.

How to Use the ColorMap

You can specify the colormap with the keyword argument cmap with the value of the colormap, in this case 'viridis' which is one of the built-in colormaps available in Matplotlib.

In addition you have to create an array with values (from 0 to 100), one value for each point in the scatter plot:

You can include the colormap in the drawing by including the plt.colorbar() statement:

Name

 

Reverse

Accent

Try it »

 

Accent_r

Try it »

Blues

Try it »

 

Blues_r

Try it »

BrBG

Try it »

 

BrBG_r

Try it »

BuGn

Try it »

 

BuGn_r

Try it »

BuPu

Try it »

 

BuPu_r

Try it »

CMRmap

Try it »

 

CMRmap_r

Try it »

Dark2

Try it »

 

Dark2_r

Try it »

GnBu

Try it »

 

GnBu_r

Try it »

Greens

Try it »

 

Greens_r

Try it »

Greys

Try it »

 

Greys_r

Try it »

OrRd

Try it »

 

OrRd_r

Try it »

Oranges

Try it »

 

Oranges_r

Try it »

PRGn

Try it »

 

PRGn_r

Try it »

Paired

Try it »

 

Paired_r

Try it »

Pastel1

Try it »

 

Pastel1_r

Try it »

Pastel2

Try it »

 

Pastel2_r

Try it »

PiYG

Try it »

 

PiYG_r

Try it »

PuBu

Try it »

 

PuBu_r

Try it »

PuBuGn

Try it »

 

PuBuGn_r

Try it »

PuOr

Try it »

 

PuOr_r

Try it »

PuRd

Try it »

 

PuRd_r

Try it »

Purples

Try it »

 

Purples_r

Try it »

RdBu

Try it »

 

RdBu_r

Try it »

RdGy

Try it »

 

RdGy_r

Try it »

RdPu

Try it »

 

RdPu_r

Try it »

RdYlBu

Try it »

 

RdYlBu_r

Try it »

RdYlGn

Try it »

 

RdYlGn_r

Try it »

Reds

Try it »

 

Reds_r

Try it »

Set1

Try it »

 

Set1_r

Try it »

Set2

Try it »

 

Set2_r

Try it »

Set3

Try it »

 

Set3_r

Try it »

Spectral

Try it »

 

Spectral_r

Try it »

Wistia

Try it »

 

Wistia_r

Try it »

YlGn

Try it »

 

YlGn_r

Try it »

YlGnBu

Try it »

 

YlGnBu_r

Try it »

YlOrBr

Try it »

 

YlOrBr_r

Try it »

YlOrRd

Try it »

 

YlOrRd_r

Try it »

afmhot

Try it »

 

afmhot_r

Try it »

autumn

Try it »

 

autumn_r

Try it »

binary

Try it »

 

binary_r

Try it »

bone

Try it »

 

bone_r

Try it »

brg

Try it »

 

brg_r

Try it »

bwr

Try it »

 

bwr_r

Try it »

cividis

Try it »

 

cividis_r

Try it »

cool

Try it »

 

cool_r

Try it »

coolwarm

Try it »

 

coolwarm_r

Try it »

copper

Try it »

 

copper_r

Try it »

cubehelix

Try it »

 

cubehelix_r

Try it »

flag

Try it »

 

flag_r

Try it »

gist_earth

Try it »

 

gist_earth_r

Try it »

gist_gray

Try it »

 

gist_gray_r

Try it »

gist_heat

Try it »

 

gist_heat_r

Try it »

gist_ncar

Try it »

 

gist_ncar_r

Try it »

gist_rainbow

Try it »

 

gist_rainbow_r

Try it »

gist_stern

Try it »

 

gist_stern_r

Try it »

gist_yarg

Try it »

 

gist_yarg_r

Try it »

gnuplot

Try it »

 

gnuplot_r

Try it »

gnuplot2

Try it »

 

gnuplot2_r

Try it »

gray

Try it »

 

gray_r

Try it »

hot

Try it »

 

hot_r

Try it »

hsv

Try it »

 

hsv_r

Try it »

inferno

Try it »

 

inferno_r

Try it »

jet

Try it »

 

jet_r

Try it »

magma

Try it »

 

magma_r

Try it »

nipy_spectral

Try it »

 

nipy_spectral_r

Try it »

ocean

Try it »

 

ocean_r

Try it »

pink

Try it »

 

pink_r

Try it »

plasma

Try it »

 

plasma_r

Try it »

prism

Try it »

 

prism_r

Try it »

rainbow

Try it »

 

rainbow_r

Try it »

seismic

Try it »

 

seismic_r

Try it »

spring

Try it »

 

spring_r

Try it »

summer

Try it »

 

summer_r

Try it »

tab10

Try it »

 

tab10_r

Try it »

tab20

Try it »

 

tab20_r

Try it »

tab20b

Try it »

 

tab20b_r

Try it »

tab20c

Try it »

 

tab20c_r

Try it »

terrain

Try it »

 

terrain_r

Try it »

twilight

Try it »

 

twilight_r

Try it »

twilight_shifted

Try it »

 

twilight_shifted_r

Try it »

viridis

Try it »

 

viridis_r

Try it »

winter

Try it »

 

winter_r

Try it »


Size

You can change the size of the dots with the s argument.

Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

Alpha

You can adjust the transparency of the dots with the alpha argument.

Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

Result:

Combine Color Size and Alpha

You can combine a colormap with different sizes of the dots. This is best visualized if the dots are transparent:

Result:

Matplotlib Bars

(Click here to go back to the menu)

Creating Bars

With Pyplot, you can use the bar() function to draw bar graphs:

The bar() function takes arguments that describes the layout of the bars.

The categories and their values represented by the first and second argument as arrays.

Horizontal Bars

If you want the bars to be displayed horizontally instead of vertically, use the barh() function:

Bar Color

The bar() and barh() take the keyword argument color to set the color of the bars:

Color Names

You can use any of the 140 supported color names.

Color Hex

Or you can use Hexadecimal color values:

Bar Width

The bar() takes the keyword argument width to set the width of the bars:

The default width value is 0.8

Note: For horizontal bars, use height instead of width.


Bar Height

The barh() takes the keyword argument height to set the height of the bars:

The default height value is 0.8

Matplotlib Histograms

(Click here to go back to the menu)

Histogram

A histogram is a graph showing frequency distributions.

It is a graph showing the number of observations within each given interval.

Example: Say you ask for the height of 250 people, you might end up with a histogram like this:

You can read from the histogram that there are approximately:

2 people from 140 to 145cm
5 people from 145 to 150cm
15 people from 151 to 156cm
31 people from 157 to 162cm
46 people from 163 to 168cm
53 people from 168 to 173cm
45 people from 173 to 178cm
28 people from 179 to 184cm
21 people from 185 to 190cm
4 people from 190 to 195cm

Create Histogram

In Matplotlib, we use the hist() function to create histograms.

The hist() function will use an array of numbers to create a histogram, the array is sent into the function as an argument.

For simplicity we use NumPy to randomly generate an array with 250 values, where the values will concentrate around 170, and the standard deviation is 10. Learn more about Normal Data Distribution in our Machine Learning Tutorial.

Result:

This will generate a random result, and could look like this:

The hist() function will read the array and produce a histogram:

Result:

Matplotlib Pie Charts

(Click here to go back to the menu)

Creating Pie Charts

With Pyplot, you can use the pie() function to draw pie charts:

Result:

As you can see the pie chart draws one piece (called a wedge) for each value in the array (in this case [35, 25, 25, 15]).

By default the plotting of the first wedge starts from the x-axis and moves counterclockwise:

Note: The size of each wedge is determined by comparing the value with all the other values, by using this formula:

The value divided by the sum of all values: x/sum(x)



Labels

Add labels to the pie chart with the labels parameter.

The labels parameter must be an array with one label for each wedge:

Result:

Start Angle

As mentioned the default start angle is at the x-axis, but you can change the start angle by specifying a startangle parameter.

The startangle parameter is defined with an angle in degrees, default angle is 0:

Result:

Explode

Maybe you want one of the wedges to stand out? The explode parameter allows you to do that.

The explode parameter, if specified, and not None, must be an array with one value for each wedge.

Each value represents how far from the center each wedge is displayed:

Result:

Shadow

Add a shadow to the pie chart by setting the shadows parameter to True:

Result:

Colors

You can set the color of each wedge with the colors parameter.

The colors parameter, if specified, must be an array with one value for each wedge:

Result:

You can use Hexadecimal color values, any of the 140 supported color names, or one of these shortcuts:

'r' - Red
'g' - Green
'b' - Blue
'c' - Cyan
'm' - Magenta
'y' - Yellow
'k' - Black
'w' - White


Legend

To add a list of explanation for each wedge, use the legend() function:

Result:

Legend With Header

To add a header to the legend, add the title parameter to the legend function.

Result:

References

w3schools.com (n.d.). Matplotlib Tutorial. [online] www.w3schools.com. Available at: https://www.w3schools.com/python/matplotlib_intro.asp.